package com.indi.gulimall.ware.config;

import com.indi.common.constant.WareConstant;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.Binding.DestinationType;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {

    /**
     * 使用JSON序列化机制对消息进行转换
     *
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

//    @RabbitListener(queues = WareConstant.STOCK_RELEASE_STOCK_QUEUE)
//    public void listener(Message message) {
//
//    }

    @Bean
    public Exchange exchange() {
        return new TopicExchange(WareConstant.STOCK_EVENT_EXCHANGE, true, false);
    }

    /**
     * 延时队列
     * @return
     */
    @Bean
    public Queue stockDelayQueue() {
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange", WareConstant.STOCK_EVENT_EXCHANGE);
        args.put("x-dead-letter-routing-key", WareConstant.STOCK_RELEASE_ROUTING_KEY);
        args.put("x-message-ttl", WareConstant.MESSAGE_TTL);
        return new Queue(WareConstant.STOCK_DELAY_QUEUE, true, false, false, args);
    }

    @Bean
    public Queue stockReleaseStockQueue() {
        return new Queue(WareConstant.STOCK_RELEASE_STOCK_QUEUE, true, false, false);
    }

    @Bean
    public Binding stockLockedBinding() {
        return new Binding(WareConstant.STOCK_DELAY_QUEUE, DestinationType.QUEUE, WareConstant.STOCK_EVENT_EXCHANGE
                , WareConstant.STOCK_LOCKED_ROUTING_KEY, null);
    }

    @Bean
    public Binding stockReleaseBinding() {
        return new Binding(WareConstant.STOCK_RELEASE_STOCK_QUEUE, DestinationType.QUEUE, WareConstant.STOCK_EVENT_EXCHANGE,
                WareConstant.STOCK_RELEASE_BINDING, null);
    }
}
